package cn.xingzhe.monster.user.infrastructure.repository.impl;

import cn.xingzhe.monster.user.domain.model.PermissionModel;
import cn.xingzhe.monster.user.domain.repository.PermissionRepository;
import cn.xingzhe.monster.user.infrastructure.persistence.converter.PermissionEntityConverter;
import cn.xingzhe.monster.user.infrastructure.persistence.entity.PermissionEntity;
import cn.xingzhe.monster.user.infrastructure.repository.PermissionMongoRepository;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * MongoDB 权限仓储实现
 * 内部操作 PermissionEntity，对外返回 PermissionModel
 *
 * @author System
 * @version 1.0.0
 * @since 2024-01-01
 */
@Component
public class MongoPermissionRepository implements PermissionRepository {

    private final PermissionMongoRepository mongoRepository;

    public MongoPermissionRepository(PermissionMongoRepository mongoRepository) {
        this.mongoRepository = mongoRepository;
    }

    @Override
    public Optional<PermissionModel> findById(String id) {
        return mongoRepository.findById(id)
                .map(PermissionEntityConverter::toModel);
    }

    @Override
    public Optional<PermissionModel> findByPermissionCode(String permissionCode) {
        return mongoRepository.findByPermissionCode(permissionCode)
                .map(PermissionEntityConverter::toModel);
    }

    @Override
    public List<PermissionModel> findByIds(List<String> ids) {
        List<PermissionEntity> entities = mongoRepository.findAllById(ids);
        return entities.stream()
                .map(PermissionEntityConverter::toModel)
                .collect(Collectors.toList());
    }

    @Override
    public PermissionModel save(PermissionModel permission) {
        PermissionEntity entity = PermissionEntityConverter.toEntity(permission);
        PermissionEntity savedEntity = mongoRepository.save(entity);
        return PermissionEntityConverter.toModel(savedEntity);
    }

    @Override
    public void deleteById(String id) {
        mongoRepository.deleteById(id);
    }

    @Override
    public List<PermissionModel> findAll() {
        List<PermissionEntity> entities = mongoRepository.findAll();
        return entities.stream()
                .map(PermissionEntityConverter::toModel)
                .collect(Collectors.toList());
    }

}

